const WebpackDevServer = require('webpack-dev-server');
const webpack = require('webpack');
const open = require('open');
const config = require('./webpack/webpack.beta.config');
const print = require('./util/print-log');
const getTime = require('./util/util');

// 启动函数
async function runDev() {
	// 申明Node端口
	let serverPort = 0;
	const { port, host } = config.devServer;

	// node接口启动的端口要避免和devServer的端口冲突
	serverPort = port + 1;
	// 增加代理配置
	Object.assign(config.devServer, {
		proxy: {
			'/api/*': {
				target: `http://${host}:${serverPort}`
			}
		},
	})

	const compiler = webpack(config);
	const server = new WebpackDevServer(compiler, config.devServer);
	server.listen(port, host, (err) => {
		if (err) {
			print.err(`${getTime()} 启动出错：${err}`);
		} else {
			open(`http://${host}:${port}/index.html`);
		}
	});
	print.info(`${getTime()} Node运行端口：${port}; devServer运行端口：${serverPort}`);
}

runDev()
